package com.becca.cake.core.web.servlet;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 生成验证码
 * @author hejinguo
 * @version $Id: SimpleCaptchaServlet.java, v 0.1 2013-9-14 下午01:26:46
 */
public class SimpleCaptchaServlet extends HttpServlet implements Servlet {
    private static final long serialVersionUID = 1L;
    protected int             _width           = 200;
    protected int             _height          = 50;

    @Override
    public void init() throws ServletException {
        if (getInitParameter("height") != null) {
            this._height = Integer.valueOf(getInitParameter("height")).intValue();
        }

        if (getInitParameter("width") != null)
            this._width = Integer.valueOf(getInitParameter("width")).intValue();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
                                                                       IOException {
        //现在的
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        // 生成图片对象
        ValidateImageUtils validateImageUtils = ValidateImageUtils.getInstance();
        // 将认证码存入SESSION
        try {
            ImageIO.write(validateImageUtils.getImage(), "JPEG", resp.getOutputStream());
        } catch (IOException ioe) {
        }
        req.getSession().setAttribute("simpleCaptcha", validateImageUtils.getRandomNum());
    }

}
